package messaging;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 * Session Bean implementation class MyProducer
 */
@Stateless
public class MyProducer implements MyProducerRemote {

	@Resource(mappedName = "jms/resourceManagerMessages")
	private ConnectionFactory connectionFactory;

	@Resource(mappedName = "jms/resourceManagerQueue")
	private Queue queue;

	MessageProducer messageProducer;
	TextMessage textMessage;
	Session session;
	Connection connection;

	/**
	 * Default constructor.
	 */
	public MyProducer() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void produceMessage() {
		try {
			connection = connectionFactory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			messageProducer = session.createProducer(queue);
			
			textMessage = session.createTextMessage();
			textMessage.setText("mesajul 1");
			messageProducer.send(textMessage);
			textMessage.setText("mesajul 2");
			messageProducer.send(textMessage);
			textMessage.setText("la revedere!");
			messageProducer.send(textMessage);

			messageProducer.close();
			session.close();
			connection.close();

		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void sendMessage(String message) {
		try {
			connection = connectionFactory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			messageProducer = session.createProducer(queue);
			
			textMessage = session.createTextMessage();
			textMessage.setText(message);

			messageProducer.close();
			session.close();
			connection.close();

		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

}
